import os
import socket
import threading
from chat_room.chat_gui_v3_with_mysql.tools import mysql
class chat_server():
    def __init__(self,host,port,outtime=100,listen=5):
        self.server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.server.bind((host,port))
        self.server.listen(listen)
        self.users_data={'wr440':'84906440'}
        self.clients=[]
    #开始运行
    def run(self):
        while True:
            client,addr=self.server.accept()
            self.client_login(client)
            self.clients.append(client)
            threading.Thread(target=self.__send_msg,args=(client,)).start()
    #用户登录
    def client_login(self,client):
        msg=client.recv(1024)#接收客户端登录数据
        if ":" in msg.decode():#判断是否为正确的登录信息
            username_login,password_login=msg.decode().split(":")#解析登录数据
            user_info,sta=mysql("select * from users where username='%s'"%(username_login))
            if sta!=0:
                user_info=self.get_mysql_data(user_info,sta)#从mysql中读取用户信息
                id,username,password,nick=user_info#解析mysql用户信息
                if password_login==password:
                    client.send("login success".encode('utf-8'))
                else:
                    client.send("error password,disconnect!".encode('utf-8'))
                    client.close()
            else:
                client.send("error username,disconnect!".encode('utf-8'))
                client.close()
        else:
            client.send("error login msg,disconnect!")
            client.close()
    def get_users_info(self):#从mysql中查询用户信息组
        data,sta=mysql('select * from users')#查询数据库users表中的信息，备注：数据库中users信息格式为id,username,password,nick
        data=self.get_mysql_data(data,sta)
        return data

    def get_mysql_data(self,data,sta):#读取mysql数据，单条信息为元组，多条信息转化为列表嵌套元组
        if sta==1:
            for i in data:
                return i
        else:
            data_list=[]
            for i in data:
                data_list.append(i)
            return data_list

    #接收用户消息然后广播
    def __send_msg(self,client):
        while True:
            try:
                msg=client.recv(1024)
            except:
                self.clients.remove(client)
                client.close()
                break
            for c in self.clients:
                if c==client:
                    pass
                else:
                    c.send(msg)
def main():
    host='192.168.0.151'
    port=9999
    cs=chat_server(host,port)
    cs.run()
if __name__=='__main__':
    main()


